package com.example.loginpage


import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.app.ActivityCompat
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import cn.smssdk.EventHandler
import cn.smssdk.SMSSDK
import com.example.loginpage.CloudSQL.MySQLConnection
import com.example.loginpage.databinding.FragmentVerifyBinding
import com.mob.MobSDK
import java.util.Timer
import java.util.TimerTask

class VerifyFragment : Fragment() {
    private lateinit var binding: FragmentVerifyBinding
    private lateinit var launcher: ActivityResultLauncher<Intent>
    private lateinit var mySQL: MySQLConnection

    private var eventHandler: EventHandler? = null
    private var count = 30
    private var timer: Timer? = null
    private var isSuccess = MutableLiveData(false)

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        MobSDK.submitPolicyGrantResult(true)
        binding = FragmentVerifyBinding.inflate(layoutInflater,container, false)
        launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){}
        mySQL = ViewModelProvider(this)[MySQLConnection::class.java]
        // 申请有关权限
        requestPhoneStatePermissions()
        binding.AccountView.setOnClickListener {
            val navCtl = findNavController()
            navCtl.navigate(R.id.action_VerifyFragment_to_AccountFragment)
        }
        launcher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){}
        isSuccess.observe(viewLifecycleOwner) {
            if (it) {
                //登录逻辑
                Toast.makeText(requireContext(), "登陆成功", Toast.LENGTH_SHORT).show()
                val intent = Intent(requireContext(), MainActivity::class.java)
                intent.putExtra(Activity_Account,binding.AccountText.text.toString())
                launcher.launch(intent)
                activity?.finish()
            }
        }
        init()
        return binding.root
    }

    override fun onDestroy() {
        super.onDestroy()
        SMSSDK.unregisterEventHandler(eventHandler)
    }

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                1 -> {
                    val remainingTime = msg.arg1
                    if (remainingTime == 0) {
                        binding.btnCode.text = "验证码"
                        // 计时结束，停止计时，恢复值
                        count = 30
                        timer?.cancel()
                        binding.btnCode.isEnabled = true
                    } else {
                        binding.btnCode.text = "$remainingTime"
                    }
                }
                2 -> Toast.makeText(requireContext(), "获取短信验证码成功", Toast.LENGTH_LONG).show()
                3 -> Toast.makeText(requireContext(), "验证失败", Toast.LENGTH_LONG).show()
                4 -> {
                    isSuccess.postValue(true)
                    Toast.makeText(requireContext(), "登录成功", Toast.LENGTH_LONG).show()
                }
            }
        }
    }

    private fun init() {

        binding.btnCode.setOnClickListener { view ->
            onClick(view)
        }
        binding.btnLogin.setOnClickListener { view ->
            onClick(view)
        }

        eventHandler = object : EventHandler() {
            override fun afterEvent(event: Int, result: Int, data: Any) {
                when(result){
                    SMSSDK.RESULT_COMPLETE->{
                        when (event) {
                            SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE -> {
                                // 提交验证码成功
                                handler.sendEmptyMessage(4)
                            }
                            SMSSDK.EVENT_GET_VERIFICATION_CODE -> {
                                // 获取验证码成功
                                handler.sendEmptyMessage(2)
                            }
                            SMSSDK.EVENT_GET_VOICE_VERIFICATION_CODE -> {
                                // 获取语音验证码成功
                                handler.sendEmptyMessage(2)
                            }
                        }
                    }
                    SMSSDK.RESULT_ERROR->{
                        // 获取验证码失败
                        handler.sendEmptyMessage(3)
                    }
                    else->{
                        // 其他失败情况
                        (data as Throwable).printStackTrace()
                    }
                }
            }
        }
        SMSSDK.registerEventHandler(eventHandler)
    }

    private fun onClick(view: View) {
        val phone: String
        val code: String
        val id = view.id
        when (id) {
            R.id.btnCode-> {
                phone = binding.AccountText.text.toString().trim { it <= ' ' }
                if (!TextUtils.isEmpty(phone)) {
                    //倒计时
                    startCountdown()
                    getVerificationCode("86", phone)
                } else {
                    Toast.makeText(requireContext(), "请输入手机号码", Toast.LENGTH_LONG).show()
                }
            }

            R.id.btnLogin -> {
                phone = binding.AccountText.text.toString().trim { it <= ' ' }
                code = binding.PasswordText.text.toString().trim { it <= ' ' }
                if(isSuccess.value == false){
                    if (TextUtils.isEmpty(phone)) {
                        Toast.makeText(requireContext(), "请输入手机号码", Toast.LENGTH_LONG).show()
                    } else if (TextUtils.isEmpty(code)) {
                        Toast.makeText(requireContext(), "请输入验证码", Toast.LENGTH_LONG).show()
                    } else {
                        submitVerificationCode("86", phone, code)
                        mySQL.updateSQL("INSERT INTO accounts (account, password) VALUES ('${binding.AccountText.text}', 'null');")
                    }
                }
            }
        }
    }
    // 倒计时函数
    private fun startCountdown() {
        binding.btnCode.isEnabled = false
        timer = Timer()
        timer!!.schedule(object : TimerTask() {
            override fun run() {
                val message = Message()
                message.what = 1
                message.arg1 = count
                handler.sendMessage(message)
                if (count != 0) {
                    count--
                } else {
                    return
                }
            }
        }, 1000, 1000)
    }

    companion object {
        const val PERMISSION_REQUEST_CODE = 128431782
        /**
         *
         * cn.smssdk.SMSSDK.class
         * 请求文本验证码
         * @param country   国家区号
         * @param phone     手机号
         */
        fun getVerificationCode(country: String?, phone: String?) {
            //获取短信验证码
            SMSSDK.getVerificationCode(country, phone)
        }
        /**
         * 提交验证码进行验证
         * @param country   国家区号
         * @param phone     手机号
         * @param code      用户输入的验证码
         */
        fun submitVerificationCode(country: String?, phone: String?, code: String) {
            // 提交验证码
            SMSSDK.submitVerificationCode(country, phone, code)
        }
    }
    // 申请有关权限
    private fun requestPhoneStatePermissions() {
        val permissions = arrayOf(
            "android.permission.READ_PHONE_STATE",
            "android.permission.SEND_SMS",
            "android.permission.RECEIVE_SMS",
            "android.permission.READ_SMS"
        )
        activity?.let { ActivityCompat.requestPermissions(it, permissions, PERMISSION_REQUEST_CODE) }
    }
}